"""
浏览器跨域代理。
"""
import aiohttp
from tornado import web


class CorsProxyHandler(web.RequestHandler):
    """
    为了解决web前端跨域问题而设计。
    """

    async def get(self):
        """
        处理跨域。
        """
        url = self.get_argument('url')
        self.add_header('Access-Control-Allow-Origin', '*')
        self.add_header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
        async with aiohttp.ClientSession() as sess:
            async with sess.get(url) as res:
                self.set_header('Content-Type', res.headers['Content-Type'])
                stream = res.content
                buf = await stream.readany()
                while buf:
                    self.write(buf)
                    buf = await stream.readany()
        await self.finish()

    async def options(self):
        """
        处理跨域。
        """
        return await self.get()
